package com.ruoyi.classai.service.impl;


import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.classai.domain.EwcTeacher;
import com.ruoyi.classai.domain.PxTrainingTeacher;
import com.ruoyi.classai.domain.dto.px.PxTrainingTeacherDto;
import com.ruoyi.classai.domain.dto.px.PxTrainingTeacherExportDto;
import com.ruoyi.classai.domain.dto.px.PxTrainingTeacherInfoDto;
import com.ruoyi.classai.domain.vo.px.PxTrainingTeacherVo;
import com.ruoyi.classai.mapper.EwcTeacherMapper;
import com.ruoyi.classai.service.IEwcTeacherService;
import com.ruoyi.classai.service.IPxTrainingTeacherService;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 教师信息Service业务层处理
 * 
 * @author lcj
 * @date 2025-02-27
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class EwcTeacherServiceImpl extends MPJBaseServiceImpl<EwcTeacherMapper, EwcTeacher> implements IEwcTeacherService {

    @Lazy
    @Autowired
    private IPxTrainingTeacherService trainingTeacherService;


    @Override
    public void addTrainingTeacher(PxTrainingTeacherDto trainingTeacherDto) {
        //查询老师是否已存在
        EwcTeacher teacher=this.getOne(Wrappers.<EwcTeacher>lambdaQuery().eq(EwcTeacher::getTeacherNo,trainingTeacherDto.getTeacherPhone())
                .eq(EwcTeacher::getStatus,Constants.COMMON_SUCCESS));
        if (Objects.isNull(teacher)) {
            teacher=new EwcTeacher();
            teacher.setTeacherName(trainingTeacherDto.getTeacherName());
            teacher.setTeacherNo(trainingTeacherDto.getTeacherPhone());
            teacher.setTeacherPhone(trainingTeacherDto.getTeacherPhone());
            teacher.setTitle(trainingTeacherDto.getTeacherPosition());
            teacher.setPassword(DigestUtil.md5Hex(Constants.INITIAL_PASSWORD));
            teacher.setSchoolId(SecurityUtils.getLoginUser().getSysUser().getSchoolId());
            this.save(teacher);
        }else {
            //更新老师名称
            teacher.setTeacherName(trainingTeacherDto.getTeacherName());
            this.updateById(teacher);
        }
        //查询老师是否已关联
        PxTrainingTeacher trainingTeacher=trainingTeacherService.getOne(Wrappers.<PxTrainingTeacher>lambdaQuery().eq(PxTrainingTeacher::getTeacherId,teacher.getId())
                .eq(PxTrainingTeacher::getTrainingId,trainingTeacherDto.getTrainingId()));
        if (Objects.nonNull(trainingTeacher)){
            throw new GlobalException("该老师已添加，不能重复添加");
        }
        //添加培训老师关联
        trainingTeacher=new PxTrainingTeacher();
        trainingTeacher.setTeacherId(teacher.getId());
        trainingTeacher.setTrainingId(trainingTeacherDto.getTrainingId());
        trainingTeacher.setTeacherNumber(trainingTeacherDto.getTeacherNumber());
        trainingTeacher.setTeacherUnit(trainingTeacherDto.getTeacherUnit());
        trainingTeacher.setTeacherPosition(trainingTeacherDto.getTeacherPosition());
        trainingTeacherService.save(trainingTeacher);
    }

    @Override
    public void editTrainingTeacher(PxTrainingTeacherDto trainingTeacherDto) {
        //查询老师是否已存在
        EwcTeacher teacher=this.getById(trainingTeacherDto.getId());
        if (Objects.isNull(teacher)) {
           throw new GlobalException("没有查询到学员信息");
        }
        //手机号不相同
        if (!Objects.equals(teacher.getTeacherPhone(),trainingTeacherDto.getTeacherPhone())){
            EwcTeacher teacher1=this.getOne(Wrappers.<EwcTeacher>lambdaQuery().eq(EwcTeacher::getTeacherNo,trainingTeacherDto.getTeacherPhone())
                    .eq(EwcTeacher::getStatus,Constants.COMMON_SUCCESS));
            if (Objects.nonNull(teacher1)){
                throw new GlobalException("学员手机号已经存在,不能修改");
            }
        }
        teacher.setTeacherName(trainingTeacherDto.getTeacherName());
        teacher.setTeacherPhone(trainingTeacherDto.getTeacherPhone());
        teacher.setTeacherNo(trainingTeacherDto.getTeacherPhone());
        teacher.setTitle(trainingTeacherDto.getTeacherPosition());
        this.updateById(teacher);
        //查询老师是否已关联
        PxTrainingTeacher trainingTeacher=trainingTeacherService.getOne(Wrappers.<PxTrainingTeacher>lambdaQuery().eq(PxTrainingTeacher::getTeacherId,teacher.getId())
                .eq(PxTrainingTeacher::getTrainingId,trainingTeacherDto.getTrainingId()));
        if (Objects.nonNull(trainingTeacher)){ //更新关联信息
            //更新培训老师关联
            trainingTeacher.setTeacherNumber(trainingTeacherDto.getTeacherNumber());
            trainingTeacher.setTeacherUnit(trainingTeacherDto.getTeacherUnit());
            trainingTeacher.setTeacherPosition(trainingTeacherDto.getTeacherPosition());
            trainingTeacherService.updateById(trainingTeacher);
        }

    }

    @Override
    public void updateTeacherByWxmini(PxTrainingTeacherInfoDto trainingTeacherInfoDto) {
        EwcTeacher teacher=this.getById(trainingTeacherInfoDto.getId());
        //查询手机号是否一致
        if (!Objects.equals(teacher.getTeacherPhone(),trainingTeacherInfoDto.getTeacherPhone())){
            EwcTeacher teacher1=this.getOne(Wrappers.<EwcTeacher>lambdaQuery().eq(EwcTeacher::getTeacherNo,trainingTeacherInfoDto.getTeacherPhone())
                    .eq(EwcTeacher::getStatus,Constants.COMMON_SUCCESS));
            if (Objects.nonNull(teacher1)){
                throw new GlobalException("学员手机号已经存在,不能修改");
            }
        }
        //查询手机号是否为空
        if (StringUtils.isNotEmpty(trainingTeacherInfoDto.getTeacherPhone())&&StringUtils.isNotEmpty(trainingTeacherInfoDto.getSmsCode())){
            //todo 验证验证码
            //修改手机号
            teacher.setTeacherPhone(trainingTeacherInfoDto.getTeacherPhone());
            teacher.setTeacherNo(trainingTeacherInfoDto.getTeacherPhone());
        }else {
            teacher.setTeacherPhone(trainingTeacherInfoDto.getTeacherPhone());
            teacher.setTeacherNo(trainingTeacherInfoDto.getTeacherPhone());
            teacher.setTeacherName(trainingTeacherInfoDto.getTeacherName());
            teacher.setTeacherEmail(trainingTeacherInfoDto.getTeacherEmail());
            teacher.setGender(trainingTeacherInfoDto.getGender());
            teacher.setPhotoPath(trainingTeacherInfoDto.getPhotoPath());
        }
        this.updateById(teacher);
    }

    @Override
    public List<PxTrainingTeacherVo> getTrainingTeacherList(String trainingId) {
        MPJLambdaWrapper<EwcTeacher> wrapper= new MPJLambdaWrapper<>();
        wrapper.selectAll(EwcTeacher.class)
                .select(PxTrainingTeacher::getTeacherUnit,PxTrainingTeacher::getTeacherNumber,PxTrainingTeacher::getTeacherPosition)
                .innerJoin(PxTrainingTeacher.class,PxTrainingTeacher::getTeacherId,EwcTeacher::getId)
                .eq(PxTrainingTeacher::getTrainingId, trainingId)
                .eq(EwcTeacher::getStatus, Constants.COMMON_SUCCESS)
                .orderByDesc(EwcTeacher::getCreateTime);
        // 执行查询并返回结果列表
        return this.selectJoinList(PxTrainingTeacherVo.class, wrapper);
    }

    @Override
    public void removeTrainingTeacher(String teacherId,String trainingId) {
//        EwcTeacher ewcTeacher=new EwcTeacher();
//        ewcTeacher.setStatus(Constants.COMMON_DELETE);
//        ewcTeacher.setId(teacherId);
        //删除关联
        trainingTeacherService.remove(Wrappers.<PxTrainingTeacher>lambdaQuery()
                .eq(PxTrainingTeacher::getTeacherId,teacherId)
                .eq(PxTrainingTeacher::getTrainingId,trainingId));
    }

    @Override
    public JSONObject importTeacher(MultipartFile file, String trainingId) {
        ExcelUtil<PxTrainingTeacherExportDto> util = new ExcelUtil<>(PxTrainingTeacherExportDto.class);
        List<PxTrainingTeacherExportDto> teacherList;
        try {
            teacherList = util.importExcel(file.getInputStream());
        } catch (IOException e) {
            throw new GlobalException(e.getMessage());
        }
        //成功
        List<String> successList=new ArrayList<>();
        //失败
        List<String> failList=new ArrayList<>();
        //学生dto循环
        for (PxTrainingTeacherExportDto teacherExportDto : teacherList) {
            if (StringUtils.isNotEmpty(teacherExportDto.getTeacherName())&&StringUtils.isNotEmpty(teacherExportDto.getTeacherPhone())
                    &&StringUtils.isNotEmpty(teacherExportDto.getTeacherNumber())) {
                //查询学生是否存在
                EwcTeacher teacher = this.getOne(Wrappers.<EwcTeacher>lambdaQuery().eq(EwcTeacher::getTeacherNo, teacherExportDto.getTeacherPhone())
                        .eq(EwcTeacher::getStatus,Constants.COMMON_SUCCESS));
                if (Objects.isNull(teacher)) {
                    teacher=new EwcTeacher();
                    teacher.setTeacherName(teacherExportDto.getTeacherName());
                    teacher.setTeacherNo(teacherExportDto.getTeacherPhone());
                    teacher.setTeacherPhone(teacherExportDto.getTeacherPhone());
                    teacher.setTitle(teacherExportDto.getTeacherPosition());
                    teacher.setPassword(DigestUtil.md5Hex(Constants.INITIAL_PASSWORD));
                    teacher.setSchoolId(SecurityUtils.getLoginUser().getSysUser().getSchoolId());
                    this.save(teacher);
                }else {
                    //更新老师名称
                    teacher.setTeacherName(teacherExportDto.getTeacherName());
                    this.updateById(teacher);
                }
                //查询老师是否已关联
                PxTrainingTeacher trainingTeacher=trainingTeacherService.getOne(Wrappers.<PxTrainingTeacher>lambdaQuery().eq(PxTrainingTeacher::getTeacherId,teacher.getId())
                        .eq(PxTrainingTeacher::getTrainingId,trainingId));
                if (Objects.nonNull(trainingTeacher)){
                    log.info("该老师已添加，不在重复添加");
                    successList.add(teacherExportDto.getTeacherName()+"学员信息添加成功");
                }else {
                    //添加培训老师关联
                    trainingTeacher = new PxTrainingTeacher();
                    trainingTeacher.setTeacherId(teacher.getId());
                    trainingTeacher.setTrainingId(trainingId);
                    trainingTeacher.setTeacherNumber(teacherExportDto.getTeacherNumber());
                    trainingTeacher.setTeacherUnit(teacherExportDto.getTeacherUnit());
                    trainingTeacher.setTeacherPosition(teacherExportDto.getTeacherPosition());
                    trainingTeacherService.save(trainingTeacher);
                    successList.add(teacherExportDto.getTeacherName()+"学员信息添加成功");
                }
            }else {
                failList.add(teacherExportDto.getTeacherName()+"学员上传失败,学员信息不完善");
            }
        }
        JSONObject resJson=new JSONObject();
        resJson.put("successList",successList);
        resJson.put("failList",failList);
        return resJson;
    }
}
